﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Threading;

namespace S7
{
	/// <summary>
	/// Interaction logic for ShowLoggedInAccounts.xaml
	/// </summary>
	public partial class ShowLoggedInAccounts : Window
	{
		public ShowLoggedInAccounts()
		{
			this.InitializeComponent();
			
			// Insert code required on object creation below this point.
		}

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Thread thr = new Thread(new ThreadStart(() =>
                {
                    try
                    {
                        Customer.lstCustomers = Customer.OnlineCustomers();
                        lbAccounts.Dispatcher.Invoke(new ThreadStart(() =>
                        {
                            lbAccounts.ItemsSource = Customer.lstCustomers;
                        }), null);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error!", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
                    }
                }));
            thr.IsBackground = true;
            thr.Start();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Customer.lstCustomers = null;
        }


        private void tbSearch_KeyUp(object sender, KeyEventArgs e)
        {
            string text = tbSearch.Text;
            if (text == "")
            {
                lbAccounts.ItemsSource = Customer.lstCustomers;
            }
            else
            {
                Thread thrSearch = new Thread(new ThreadStart(() =>
                {
                    while (true)
                    {
                        if (Customer.lstCustomers == null)
                        {
                            Thread.Sleep(50);
                        }
                        else
                        {
                            List<Customer> lstItems = Customer.SearchText(text);
                            lbAccounts.Dispatcher.Invoke(new ThreadStart(() =>
                            {
                                lbAccounts.ItemsSource = lstItems;
                            }), null);
                            break;
                        }
                    }
                }));
                thrSearch.IsBackground = true;
                thrSearch.Start();
            }
        }
	}
}